﻿using Newtonsoft.Json;
using OfficeMiddlewareCore;
using System;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime.ConstrainedExecution;
using System.Windows.Forms;
using WebSocketSharp;
using WebSocketSharp.Server;

namespace OfficeMiddleware
{
    public class MainHub : WebSocketBehavior
    {
        private static object _lockObj = new object();
        protected override void OnMessage(MessageEventArgs e)
        {
            var msg = e.Data;
            WsDto dto = null;
            try
            {
                dto = JsonConvert.DeserializeObject<WsDto>(msg);
                if (string.IsNullOrWhiteSpace( dto.DocCode))
                {
                    WebSocketResponse.Create(CoreResponseStatus.非法Json对象, dto.DocCode, "文档id不能为空");
                    return;
                }
                if (dto.OptType == null)
                {
                    WebSocketResponse.Create(CoreResponseStatus.非法Json对象, dto.DocCode, "操作类型不能为空");
                    return;
                }
                lock (_lockObj)
                {
                    if (dto.OptType == OptType.查看版本)
                    {
                        var ver = Assembly.GetExecutingAssembly().GetName().Version.ToString();
                        WebSocketResponse.Create(CoreResponseStatus.操作成功, dto.DocCode, ver);
                        return;
                    }
                    else if (dto.OptType == OptType.打开文件夹)
                    {
                        if (!Directory.Exists(dto.FilePath))
                        {
                            Directory.CreateDirectory(dto.FilePath);
                        }
                        Process.Start("explorer.exe", "\"" + dto.FilePath + "\"");
                        WebSocketResponse.Create(CoreResponseStatus.操作成功, dto.DocCode);
                        return;
                    }
                    else
                    {
                        if (dto.FileVersion == default) dto.FileVersion = 1;
                        dto.Execute();

                    }
                }
                // Action(dto);
            }
            catch (JsonSerializationException jse)
            {
                LogHelper.Error(jse.Message, jse);
                WebSocketResponse.Create(CoreResponseStatus.非法Json对象);
            }
            catch (Exception ex)
            {
                LogHelper.Error(ex.Message, ex);
                WebSocketResponse.Create(CoreResponseStatus.其它异常, dto);

            }
        }

    }
}
